package com.bingqing.controller;

import cn.hutool.core.date.DateUtil;
import com.bingqing.common.Result;
import com.bingqing.dao.HotelDao;
import com.bingqing.entity.Hotel;
import com.bingqing.entity.Params;
import com.bingqing.entity.Reserve;
import com.bingqing.service.HotelService;
import com.bingqing.service.ReserveService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * ClassName: TypeController
 * Package: com.bingqing.controller
 * Description:
 *
 * @Author liuyujie
 * @Create 2024-03-10 9:24
 * @Version 1.0
 */
@RestController
@RequestMapping("/reserve")
public class ReserveController {
    @Resource
    ReserveService reserveService;

    @Resource
    HotelDao hotelDao;

    //分页查询
    @GetMapping("/search")
    public Result findBySearch(Params params) {
        PageInfo<Reserve> info = reserveService.findBySearch(params);
        return Result.success(info);
    }


    //预定
    @PostMapping("/save")
    public Result save(@RequestBody Reserve reserve) {
        //1.判断酒店剩余房间是否为0，大于0的时候，才可以被预定
        Hotel hotel = hotelDao.selectByPrimaryKey(reserve.getHotelId());
        if(hotel.getNum() == 0){
            return Result.error("酒店该房间已预定完，请预定其他房间！");
        }
        //2.往预定表里插入一条预定记录
        reserve.setCreateTime(DateUtil.now());
        reserve.setUpdateTime(DateUtil.now());
        reserveService.add(reserve);
        //3.对应的酒店房间剩余数量减1
        hotel.setNum(hotel.getNum() - 1);
        hotelDao.updateByPrimaryKeySelective(hotel);

        return Result.success();
    }
    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        reserveService.deleteById(id);
        return Result.success();
    }

}
